package com.repro.baselib.lib_base.network.interceptors

import android.text.TextUtils
import android.util.Log
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.RequestBody
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
import java.net.URLDecoder
import okhttp3.MediaType.Companion.toMediaType

/**
 * 更改请求体里面数据媒体类型 post请求的时候body改为json类型
 */
class ParamsInterceptor : Interceptor{

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val headIgnoreParamsFormat = (request.header("IgnoreParamsArrayFormat"))==("1")
        when (request.method) {
            "GET" -> {

            }
            "POST" -> {
                if (request.body==null){//body为空的时候创建一个空的json对象
                    val jsonObject = JSONObject()
                    val requestBody = RequestBody.create("application/json; charset=UTF-8".toMediaType(),jsonObject.toString())
                    return chain.proceed(request.newBuilder().post(requestBody).build())
                }else{
                    request.body?.let {
                        if (it is FormBody){
                            val jsonObject = JSONObject()
                            for (i in 0 until it.size){
                                val encodeValue = it.encodedValue(i)
                                val decodeValue = URLDecoder.decode(encodeValue,"UTF-8")

                                if (!TextUtils.isEmpty(decodeValue)) {
                                    val next= (JSONTokener(decodeValue).nextValue())
                                    if (next is JSONArray  && !headIgnoreParamsFormat) {
                                        val jsonArray = JSONArray(decodeValue.toString())
                                        jsonObject.put(it.encodedName(i), jsonArray)
                                    } else  {
                                        jsonObject.put(it.encodedName(i), decodeValue.toString())
                                    }
                                }else{
                                    jsonObject.put(it.encodedName(i), "")
                                }
                            }
                            val requestBody = RequestBody.create("application/json; charset=UTF-8".toMediaType(),jsonObject.toString())
                            return chain.proceed(request.newBuilder().post(requestBody).build())
                        }
                    }
                }
            }
        }
        return chain.proceed(request)
    }
}